from tkinter.messagebox import showinfo

import windnd
import tkinter as tk
from ftp_client_alter_bug.tree.ftp_tree import FtpTree


class FtpDrag():
    def __init__(self, right_frame, ftp_path, ftp_list, win_path, bommot_frame_center, tree_ftp):
        self.right_frame = right_frame
        self.ftp_path = ftp_path
        self.ftp_list = ftp_list
        self.win_path = win_path
        self.bommot_frame_center = bommot_frame_center
        self.tree_ftp = tree_ftp

    def win_file(self, files):
        msg = "\n".join((item.decode("gbk") for item in files))
        print(msg)
        # with open(msg, mode="rb+") as re:
        #     buffer = re.read()
        # with open(self.win_path[0] + "\\" + msg.split("\\")[-1], mode="wb+") as wr:
        #     wr.write(buffer)
        try:
            def uploadfile(ftp, remotepath, localpath):
                bufsize = 1024
                fp = open(localpath, 'rb')
                ftp.storbinary(r'STOR ' + rf'{remotepath}', fp, bufsize)  # 上传文件
                ftp.set_debuglevel(0)
                fp.close()


            uploadfile(self.ftp_list[0], self.ftp_list[0].pwd() + "\\" + msg.split("\\")[-1], msg)

            # 更新进度条函数
            def change_schedule(now_schedule, all_schedule):
                canvas.coords(fill_rec, (5, 5, 6 + (now_schedule / all_schedule) * 100, 25))
                self.bommot_frame_center.update()
                x.set(str(round(now_schedule / all_schedule * 100, 2)) + '%')
                if round(now_schedule / all_schedule * 100, 2) == 100.00:
                    x.set("完==成==了")

            canvas = tk.Canvas(self.bommot_frame_center, width=110, height=30, bg="white")
            canvas.place(x=150, y=25)
            x = tk.StringVar()
            # 进度条以及完成程度
            out_rec = canvas.create_rectangle(5, 5, 105, 25, outline="blue", width=1)
            fill_rec = canvas.create_rectangle(5, 5, 5, 25, outline="", width=0, fill="blue")

            tk.Label(self.bommot_frame_center, textvariable=x, font=("宋体", 13)).place(x=280, y=30)

            for i in range(100):
                change_schedule(i, 99)

            if str(self.ftp_list[0].pwd().encode('iso-8859-1').decode('GB18030')) != "/":
                table = self.tree_ftp
                items = table.get_children()
                [table.delete(item) for item in items]
                ftptree = FtpTree(self.ftp_path, self.ftp_list, self.tree_ftp)
                ftptree.xianshi(self.ftp_list[0].pwd().encode('iso-8859-1').decode('GB18030'))
            else:
                table = self.tree_ftp
                items = table.get_children()
                [table.delete(item) for item in items]
                ftptree = FtpTree(self.ftp_path, self.ftp_list, self.tree_ftp)
                ftptree.xianshi("/")
        except:
            showinfo("错误提示", "服务器连接异常!")

    def execute(self):
        windnd.hook_dropfiles(self.right_frame, func=self.win_file)